package com.gonsin.gview.common.utils;

import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.TypeHandler;

import javax.persistence.AttributeConverter;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

public class MapJsonHandler implements TypeHandler<Map<String, Object>>, AttributeConverter<Map<String, Object>, String> {
    @Override
    public void setParameter(PreparedStatement preparedStatement, int i, Map<String, Object> stringObjectMap, JdbcType jdbcType) throws SQLException {
        String json = stringObjectMap == null ? "{}" : new Gson().toJson(stringObjectMap);
        preparedStatement.setString(i, json);
    }

    @Override
    public Map<String, Object> getResult(ResultSet resultSet, String s) throws SQLException {
        String json = resultSet.getString(s);
        if(StringUtils.isEmpty(json)){
            return new HashMap<>();
        }

        return new Gson().fromJson(json, new TypeToken<Map<String, Object>>(){}.getType());
    }

    @Override
    public Map<String, Object> getResult(ResultSet resultSet, int i) throws SQLException {
        return null;
    }

    @Override
    public Map<String, Object> getResult(CallableStatement callableStatement, int i) throws SQLException {
        return null;
    }

    @Override
    public String convertToDatabaseColumn(Map<String, Object> stringObjectMap) {
        String json = stringObjectMap == null ? "{}" : new Gson().toJson(stringObjectMap);
        return json;
    }

    @Override
    public Map<String, Object> convertToEntityAttribute(String json) {
        if(StringUtils.isEmpty(json)){
            return new HashMap<>();
        }
        return new Gson().fromJson(json, new TypeToken<Map<String, Object>>(){}.getType());
    }
}
